package com.homwee.factory.pageData;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import com.homwee.factory.FactoryActivity;
import com.homwee.factory.FactoryWriteMacActivity;
import com.homwee.factory.R;
import com.homwee.factory.util.Contants;
import com.homwee.factory.util.view.FactoryKeyResultDialog;
import com.homwee.listMenu.util.MenuItemData;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;

//zcj 2018-10-30 import com.changhong.tvos.service.TvMiscManager;

public class PageData2 extends PageData {

    private String macStr;
    private String deviceIdStr;
    private String barcodeInfoStr;
    private String ipAddressStr;
    private String screenCsStr;
    private Context context;

    private Handler mHandler = new Handler();
    public static Toast mToast = null;

    public PageData2(Context context, FactoryActivity mFactoryActivity) {
        super(mFactoryActivity);
        this.context = context;

    }

    private MenuItemData macAdress;
    private MenuItemData deviceId;

    public List<MenuItemData> LoadPageData() {
        mListItemData.clear();

        String netDetectionStr = mFactoryActivity.getResources().getString(
                R.string.factory_network_detection);
        MenuItemData netDetection = new MenuItemData(netDetectionStr);
        netDetection.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                Log.v("tv", "onEnterRightKey");
                Intent netIntent = new Intent("android.settings.WIFI_SETTINGS");
                try {
                    mContext.startActivity(netIntent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });

        String reloadEepromStr = "Reload Eeprom";
        MenuItemData reloadEeprom = new MenuItemData(reloadEepromStr);
        reloadEeprom.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                Log.v("tv", "onEnterRightKey");
//                Intent netIntent = new Intent("android.settings.WIFI_SETTINGS");
                try {
		Intent intent = new Intent();
		intent.setPackage("com.mediatek.tv.factorykey");
		intent.setAction("com.mediatek.tv.factorykey.ReloadEeprom");
		mContext.startService(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        macStr = factorySetting.getMAC();
        macAdress = new MenuItemData(macStr, mFactoryActivity.getResources()
                .getString(R.string.factory_mac_address), macStr,
                MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);

        deviceIdStr = factorySetting.getDeviceID();
        deviceIdStr = "N/A";
        deviceId = new MenuItemData(deviceIdStr, mFactoryActivity
                .getResources().getString(R.string.factory_device_id),
                deviceIdStr, MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);

        barcodeInfoStr = factorySetting.getPID();
        MenuItemData BarcodeInfo = new MenuItemData(barcodeInfoStr,
                mFactoryActivity.getResources().getString(
                        R.string.factory_bar_code_information), barcodeInfoStr,
                MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);

        ipAddressStr = factorySetting.getIPAdress();
        MenuItemData ipAddress = new MenuItemData(ipAddressStr,
                mFactoryActivity.getResources().getString(
                        R.string.factory_ip_address), ipAddressStr,
                MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);

        String manualSetMacStr = mFactoryActivity.getResources().getString(
                R.string.factory_mac_writing);
        MenuItemData manualSetMac = new MenuItemData(manualSetMacStr);
        manualSetMac.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                Log.v("tv", "onEnterRightKey");

                Intent intent = new Intent(context,
                        FactoryWriteMacActivity.class);
                intent.putExtra("mac", macStr);
                mFactoryActivity.startActivityForResult(intent, 1);
            }
        });

        String usbUpdateMacStr = mFactoryActivity.getResources().getString(
                R.string.factory_usb_mac);
        MenuItemData usbUpdateMac = new MenuItemData(usbUpdateMacStr);
        usbUpdateMac.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                // mFactoryActivity.showMenu(false);
                Log.v("tv", "onEnterRightKey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_MAC);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setMACAddr(mFile.listFiles()[0]
                                    .getAbsolutePath())) {
                                //factorySetting.deleteFileByPath(mFile
                                //        .listFiles()[0].getAbsolutePath());
								showToast(context.getString(R.string.factory_pagetwo_key_update_success));
							}else{
								showToast(context.getString(R.string.factory_pagetwo_key_update_error));
                            }
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        String usbUpdateDeviceStr = mFactoryActivity.getResources().getString(
                R.string.factory_pagetwo_device_upgrade);
        MenuItemData usbUpdateDeviceID = new MenuItemData(usbUpdateDeviceStr);
        usbUpdateDeviceID.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                // mFactoryActivity.showMenu(false);
                Log.v("tv", "onEnterRightKey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_DEVICEID);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setDeviceIDByPath(mFile.listFiles()[0]
                                    .getAbsolutePath())) {
                                factorySetting.deleteFileByPath(mFile
                                        .listFiles()[0].getAbsolutePath());
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            }
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        /*
         * String usbUpdateDeviceIdStr = mFactoryActivity.getResources()
         * .getString(R.string.factory_usb_device_id); MenuItemData
         * usbUpdateDeviceId = new MenuItemData(usbUpdateDeviceIdStr,
         * usbUpdateDeviceIdStr, "N/A", EN_ItemType.EN_OPTIONTEXTVIEW);
         */

        String backupDataUsbStr = mFactoryActivity.getResources().getString(
                R.string.factory_backup_data_usb);
        MenuItemData backupDataUsb = new MenuItemData(backupDataUsbStr);
        backupDataUsb.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                if (factorySetting.findUsbDir()) {
                    File dataBackUpFile = factorySetting
                            .getFile("dataBackUpFile.txt");
                    try {
                        FileOutputStream fout = new FileOutputStream(
                                dataBackUpFile);
                        String macStr = factorySetting.getMAC().trim();
                        String deviceIdStr = factorySetting.getDeviceID()
                                .trim();
                        if (deviceIdStr != null) {
                            deviceIdStr = deviceIdStr.trim();
                            if (deviceIdStr.length() >= 64) {
                                deviceIdStr = deviceIdStr.substring(0, 64);
                            } else if (40 <= deviceIdStr.length()
                                    && deviceIdStr.length() < 64) {
                                deviceIdStr = deviceIdStr.substring(0, 40);
                            } else {

                            }
                        }

                        String writeStr = "MAC:" + macStr + "\r\n"
                                + "DevicesId:" + deviceIdStr + "\r\n";
                        byte[] bytes = writeStr.getBytes();

                        fout.write(bytes);
                        fout.close();
                        Toast toast = null;
                        toast = Toast.makeText(context, context
                                        .getString(R.string.factory_dataBackUpFile),
                                Toast.LENGTH_SHORT);
                        toast.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast toast = null;
                    toast = Toast.makeText(context, context
                                    .getString(R.string.factory_create_dataBackUpFile),
                            Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });

        // 6m40 cs
        screenCsStr = "" + factorySetting.getScreenCS();
        MenuItemData screenCs = new MenuItemData(screenCsStr, mFactoryActivity
                .getResources().getString(R.string.factory_screen_cs),
                screenCsStr, MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);

        // 6m40 update
        String screenUpgradeStr = mFactoryActivity.getResources().getString(
                R.string.factory_screen_upgrade);
        MenuItemData screenUpgrade = new MenuItemData(screenUpgradeStr);
        screenUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                mHandler.post(new Runnable() {
                    public void run() {
                        if (factorySetting.findUsbDir()) {
                            File pannelUpdateFile = factorySetting
                                    .getFile("panelupdate.bin");
                            if (pannelUpdateFile.exists()) {
                                String pathStr = pannelUpdateFile.getParent()
                                        + File.separator + "panelupdate.bin";
                                if (factorySetting.setBackupDataToUSB(
                                        pathStr.getBytes(), pathStr.length())) {
                                    factorySetting.reboot();
                                    Toast.makeText(context, "reboot......",
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(context,
                                            "updatePdpLogic failed",
                                            Toast.LENGTH_SHORT).show();
                                }

                            } else {
                                Toast toast = null;
                                toast = Toast.makeText(
                                        context,
                                        context.getString(R.string.factory_no_pannelupdate_file),
                                        Toast.LENGTH_SHORT);
                                toast.show();
                            }

                        } else {
                            Toast toast = null;
                            toast = Toast.makeText(
                                    context,
                                    context.getString(R.string.factory_panelupdate_bin),
                                    Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    }
                });
            }
        });

        // panel
        String screenDataUpgradeStr = mFactoryActivity.getResources()
                .getString(R.string.factory_screen_data_upgrade);
        MenuItemData screenDataUpgrade = new MenuItemData(screenDataUpgradeStr);
        screenDataUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub

                if (factorySetting.findUsbDir()) {
                    final String mFileName = Contants.FACTORY_PAGE2_PANEL_UPDATE_PATH;
                    final File pannelUpdateFile = factorySetting
                            .getFile(mFileName);

					/*final String mMstFileName = "pnl";// +factorySetting.getPanelName()+".ini";
					final File MstPannelUpdateFile = factorySetting
							.getFile(mMstFileName);*/

                    //  panel
                    if (pannelUpdateFile.exists()) {

                        final File[] panel_files = pannelUpdateFile.listFiles();
                        if (panel_files.length == 0) {
                            Toast toast = Toast.makeText(context,
                                    "Can't find any file in panel directory",
                                    Toast.LENGTH_SHORT);
                            toast.show();
                            return;
                        } else {

                            new Handler().postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    File file = panel_files[0];
                                    factorySetting.copyFile(
                                            file.getAbsolutePath(), Contants.FACTORY_PAGE2_PANEL_PATH + "/" + file.getName());
                                    factorySetting.setPanelName(file.getName().replace(".ini", ""));

                                    MtkTvFApiSystem.getInstance().setEmmcEnvVar("db_table", "0");
                                    Toast.makeText(context, "update panel ok",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }, 100);
                        }
                    } else {
                        Toast.makeText(context,
                                "Can't find panel    directory!",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // mst pnl
					/*if (MstPannelUpdateFile.exists()) {
						final File[] pnl_files = MstPannelUpdateFile
								.listFiles();
						if (pnl_files.length == 0) {
							Toast toast = Toast.makeText(context,
									"Can't find any file in panel directory",
									Toast.LENGTH_SHORT);
							toast.show();
							return;
						} else {

							new Handler().postDelayed(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									for (File file : pnl_files) {
										factorySetting.copyFile(
												file.getAbsolutePath(),
												"/hwcfg/config/pnl"
														+ File.separator
														+ file.getName());
									}

									// factorySetting.copyFile(pannelUpdateFile.getPath(),
									// "/hwcfg/panel/" + mFileName);
									// factorySetting.copyFile(MstPannelUpdateFile.getPath(),
									// "/hwcfg/config/" + mMstFileName);
									Toast.makeText(context, "update ok 2",
											Toast.LENGTH_SHORT).show();
								}

							}, 100);

						}
					} else {
						Toast.makeText(context,
								"Can't find panel    directory!",
								Toast.LENGTH_SHORT).show();
						return;
					}*/

                   /* new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            //if (factorySetting.updateCurrentPaneldata()) {
                            // zcj 2018-10-30
                            // TvMiscManager.getInstance().setATVPresetFlag(true);
                            PowerManager pManager = (PowerManager) mContext
                                    .getSystemService(mContext.POWER_SERVICE);
                            pManager.reboot("");
                            Toast.makeText(context, "reboot......",
                                    Toast.LENGTH_SHORT).show();

							} else {
								Toast.makeText(context,
										"updateCurrentPaneldata failed",
										Toast.LENGTH_SHORT).show();
							}
                        }
                    }, 1000); */

                } else {
                    Toast.makeText(context,
                            "Please insert USB,Can't find USB!",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        final File[] DataPaths=new File[Contants.mDataPathStrings.length];
        MenuItemData PorductModelUpgrade = new MenuItemData(
                "Customer Update");
        PorductModelUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                // TODO Auto-generated method stub

                mHandler.post(new Runnable() {
                    public void run() {
                    	factorySetting.customerUpdate(mContext);
                    }
                });
            }
        });

        final MenuItemData m6m40Upgrade = new MenuItemData("6m60 Upgrade");
        m6m40Upgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {

                // TODO Auto-generated method stub

                mHandler.post(new Runnable() {
                    public void run() {
                        if (factorySetting.findUsbDir()) {
                            String m6m40FileName = factorySetting
                                    .searchFile("6M40A");

                            File m6m40UpgradeFile = factorySetting
                                    .getFile(m6m40FileName);

                            if (m6m40UpgradeFile.exists()) {
                                final String pathStr = m6m40UpgradeFile
                                        .getParent()
                                        + File.separator
                                        + m6m40FileName;
                                final Dialog mDialog = new Dialog(mContext);
                                mDialog.setTitle(m6m40FileName
                                        + "Upgrading... Please wait!");
                                mDialog.show();
                                mHandler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        if (factorySetting.Update6M40bindata(
                                                pathStr.getBytes(),
                                                pathStr.length())) {
                                            Toast.makeText(
                                                    context,
                                                    "upgrade success!  Please Power off and Reboot！",
                                                    Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(context,
                                                    "update6m40 failed",
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                        mDialog.hide();
                                    }
                                }, 500);

                            } else {
                                Toast toast = null;
                                toast = Toast.makeText(context,
                                        "Can't find the file 6M40A.bin ",
                                        Toast.LENGTH_SHORT);
                                toast.show();
                            }

                            Log.v("--tag5--", "TAG");

                        } else {
                            Toast toast = null;
                            toast = Toast.makeText(
                                    context,
                                    context.getString(R.string.factory_panelupdate_bin),
                                    Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    }
                });

            }
        });
		
        final File[] mPQDirs = new File[Contants.mPQPathStrings.length];
        final MenuItemData mPQUpgrade = new MenuItemData("PQ Upgrade");
        mPQUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {
            public void onEnterRightKey() {
                // TODO Auto-generated method stub
                mHandler.post(new Runnable() {
                    public void run() {
                        if (factorySetting.findUsbDir()) {
                            final String mPQName = Contants.FACTORY_PAGE2_PQ_UPDATE_PATH;
                            Log.d("zcj", mPQName);
                            File mPQDirFile = factorySetting.getFile(mPQName);
                            final File mPQPath = new File(Contants.FACTORY_PAGE2_PQ_PATH);
                            final File mPQGeneralPath = new File(Contants.FACTORY_PAGE2_PQGENERAL_PATH);
                            final File mApolloPath = new File(Contants.FACTORY_PAGE2_APOLLO_PATH);
                            final File mPanelPath = new File(Contants.FACTORY_PAGE2_PANEL_PATH);
                            final File mColorMaPath = new File(Contants.FACTORY_PAGE2_COLORMA_PATH);
                            if (!mPQDirFile.exists()) {
                                Toast toast = Toast.makeText(context,
                                        "USB Root Directory  Can't find "
                                                + mPQName + " directory",
                                        Toast.LENGTH_SHORT);
                                toast.show();
                            } else {
                                Toast toast = Toast
                                        .makeText(
                                                context,
                                                "Upgrade success reboot to take effect!",
                                                Toast.LENGTH_LONG);
                                toast.show();
                                //copy PQiniversion
                                File PQIniFile = factorySetting.getFile(Contants.FACTORY_PAGE2_PQ_UPDATE_PATH+"/"+Contants.FACTORY_PQINI_VERSION);
                                factorySetting.copyFile(PQIniFile.getAbsolutePath(),Contants.FACTORY_PAGE2_PANEL_PATH+Contants.FACTORY_PQINI_VERSION);

                                for (int id = 0; id < Contants.mPQPathStrings.length; id++) {
                                    mPQDirs[id] = factorySetting
                                            .getFile(Contants.FACTORY_PAGE2_PQ_UPDATE_PATH + "/" + Contants.mPQPathStrings[id]);
                                }
                                for (int index = 0; index < mPQDirs.length; index++) {
                                    if (mPQDirs[index].exists() && mPQDirs[index].isDirectory()) {
                                        if (mPQDirs[index].listFiles().length > 0) {
                                            switch (index) {
                                                case Contants.PATH_TAG_APOLLO: {
                                                    for (File file : mPQDirs[index].listFiles()) {
                                                        factorySetting.copyFile(
                                                                file.getAbsolutePath(),
                                                                mApolloPath.getPath()
                                                                        + File.separator
                                                                        + file.getName());
                                                    }
                                                }
                                                break;
                                                case Contants.PATH_TAG_COLORMA: {
                                                    for (File file : mPQDirs[index].listFiles()) {
                                                        factorySetting.copyFile(
                                                                file.getAbsolutePath(),
                                                                mColorMaPath.getPath()
                                                                        + File.separator
                                                                        + file.getName());
                                                    }
                                                }
                                                break;
                                                case Contants.PATH_TAG_PANEL: {
                                                    for (File file : mPQDirs[index].listFiles()) {
                                                        factorySetting.copyFile(
                                                                file.getAbsolutePath(),
                                                                mPanelPath.getPath()
                                                                        + File.separator
                                                                        + file.getName());
                                                    }
                                                }
                                                break;
                                                case Contants.PATH_TAG_PQ: {
                                                    for (File file : mPQDirs[index].listFiles()) {
                                                        factorySetting.copyFile(
                                                                file.getAbsolutePath(),
                                                                mPQPath.getPath()
                                                                        + File.separator
                                                                        + file.getName());
                                                    }
                                                }
                                                break;
                                                case Contants.PATH_TAG_PQGENERAL: {
                                                    for (File file : mPQDirs[index].listFiles()) {
                                                        factorySetting.copyFile(
                                                                file.getAbsolutePath(),
                                                                mPQGeneralPath.getPath()
                                                                        + File.separator
                                                                        + file.getName());
                                                    }
                                                }
                                                break;

                                            }
                                        }
                                    }

                                }

                                //pq_common copy
                                final File mPqCommonPath = new File(Contants.FACTORY_PAGE2_PQ_COMMON_PATH);
                                final File mPqCommon=factorySetting
                                        .getFile(Contants.FACTORY_PAGE2_PQ_UPDATE_PATH + "/" + Contants.FACTORY_PAGE2_PQ_COMMON);
                                if(mPqCommon.exists()&&mPqCommon.isDirectory()){
                                    if(mPqCommon.listFiles().length>0){
                                        File[] pqFiles=mPqCommon.listFiles();
                                        factorySetting.copyFileSupport(pqFiles,mPqCommonPath);
                                    }
                                }


                                MtkTvFApiSystem.getInstance().setEmmcEnvVar("db_table", "0");
                               // PowerManager pManager = (PowerManager) mContext
                               //                             .getSystemService(mContext.POWER_SERVICE);
                               // pManager.reboot("");
                            }
                        } else {
                            Toast toast = null;
                            toast = Toast.makeText(
                                    context,
                                    context.getString(R.string.factory_panelupdate_bin),
                                    Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    }
                });

            }
        });

        final MenuItemData mAQUpgrade = new MenuItemData("AQ Upgrade");
        mAQUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {

                // TODO Auto-generated method stub

                mHandler.post(new Runnable() {
                    public void run() {
                        if (factorySetting.findUsbDir()) {
                            final String mAQUpdatePath = Contants.FACTORY_PAGE2_AQ_UPDATE_PATH;
                            Log.d("zcj", mAQUpdatePath);
                            File mAQDirFile = factorySetting.getFile(mAQUpdatePath);
                            final File mAQhwcfgFile = new File(Contants.FACTORY_PAGE2_AQ_PATH);
                            if (!mAQDirFile.exists()) {
                                Toast toast = Toast.makeText(context,
                                        "USB Root Directory  Can't find "
                                                + mAQUpdatePath + " directory",
                                        Toast.LENGTH_SHORT);
                                toast.show();
                            } else {
                                final File[] pq_files = mAQDirFile.listFiles();
                                if (pq_files.length == 0) {
                                    Toast toast = Toast
                                            .makeText(context,
                                                    "Can't find any file in "
                                                            + mAQUpdatePath
                                                            + " directory",
                                                    Toast.LENGTH_SHORT);
                                    toast.show();
                                } else {
                                    Toast toast = Toast
                                            .makeText(
                                                    context,
                                                    "Upgrade success reboot to take effect",
                                                    Toast.LENGTH_LONG);
                                    toast.show();
                                    if (!mAQhwcfgFile.exists()) {
                                        mAQhwcfgFile.mkdir();
                                    }

                                    new Handler().postDelayed(new Runnable() {

                                        @Override
                                        public void run() {
                                            // TODO Auto-generated method stub
                                            factorySetting.copyFileSupport(pq_files,mAQhwcfgFile);
//                                            for (File file : pq_files) {
//                                                    factorySetting.copyFile(
//                                                            file.getAbsolutePath(),
//                                                            mAQhwcfgFile.getPath()
//                                                                    + File.separator
//                                                                    + file.getName());
//
//                                            }
                                            // zcj 2018-10-30
                                            // TvMiscManager.getInstance().setATVPresetFlag(true);
                                         //   PowerManager pManager = (PowerManager) mContext
                                         //           .getSystemService(mContext.POWER_SERVICE);
                                         //   pManager.reboot("");
                                        }
                                    }, 100);

                                }

                            }


                        } else {
                            Toast toast = null;
                            toast = Toast.makeText(
                                    context,
                                    context.getString(R.string.factory_panelupdate_bin),
                                    Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    }
                });

            }
        });

        final MenuItemData mHdcp2xUpgrade = new MenuItemData(
                "HDCP2X KEY Upgrade");
        mHdcp2xUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "mHdcp2xUpgrade onkey");

                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_HDCP);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setHdcpKey2x(mFile.listFiles()[0]
                                    .getAbsolutePath())) {
								// factorySetting.deleteFileByPath(mFile
								// .listFiles()[0].getAbsolutePath());
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            } else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        final MenuItemData mHdcp1xUpgrade = new MenuItemData(
                "HDCP1X KEY Upgrade");
        mHdcp1xUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "mHdcp1xUpgrade onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_HDCP14);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setHdcpKey1x(mFile.listFiles()[0]
                                    .getAbsolutePath())) {
                                //factorySetting.deleteFileByPath(mFile
                                //        .listFiles()[0].getAbsolutePath());
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            } else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        final MenuItemData WidevineKeyUpadate = new MenuItemData(
                "Widevine KEY Upgrade");
        WidevineKeyUpadate.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "Widevine KEY onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_WIDEVINE);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            File tempfile = mFile.listFiles()[0];
							String fileName = tempfile.getName().substring(0, tempfile.getName().indexOf("."));
							if (factorySetting.setWidevineKey(tempfile.getAbsolutePath())
									&& factorySetting.setDeviceID(fileName)) {
                                //factorySetting.deleteFileByPath(tempfile.getAbsolutePath());
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            } else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        final MenuItemData CIPlusKeyUpadate = new MenuItemData(
                "CIPlus KEY Upgrade");
        CIPlusKeyUpadate.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "CIPlus KEY onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_CIPLUS);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setCIPlusKey(mFile.listFiles()[0]
                                    .getAbsolutePath())) {
                                //factorySetting.deleteFileByPath(mFile
                                //        .listFiles()[0].getAbsolutePath());
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            } else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        final MenuItemData CIPlusKeyUpadateForAuth = new MenuItemData(
                "CIPlus KEY Upgrade Auth");
        CIPlusKeyUpadateForAuth.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "CIPlus KEY onkey");
//                if (factorySetting.findUsbDir()) {
                    int ret = factorySetting.updateCIPlusKey();
                    Log.d("zcj", ret + "");
                    showToast(ret == 0 ? context
                            .getString(R.string.factory_pagetwo_key_update_success) : context
                            .getString(R.string.factory_pagetwo_key_update_error));
//                } else {
//                    showToast(context
//                            .getString(R.string.factory_reciver_no_usb));
//                }
            }
        });

		final MenuItemData ESNKeyUpadate = new MenuItemData("NETFLIX KEY Upgrade");
		ESNKeyUpadate.setOnEnterKey(new MenuItemData.onEnterRightKey() {

			public void onEnterRightKey() {
				Log.v("tv", "ESN KEY onkey");
				if (factorySetting.findUsbDir()) {
					File mFile = factorySetting
							.getFile(Contants.KEY_PATH_STRING_UPDATE_DIR+"/"+Contants.KEY_PATH_STRING_NETFLIX);
					if (mFile.exists()&&mFile.isDirectory()) {
						if (mFile.listFiles().length > 0) {
							if (factorySetting.setNetflixKey(mFile.listFiles()[0]
									.getAbsolutePath())) {
								//factorySetting.deleteDirByPath(mFile
								//		.listFiles()[0].getAbsolutePath());
								showToast(context
										.getString(R.string.factory_pagetwo_key_update_success));
							} else
								showToast(context
										.getString(R.string.factory_pagetwo_key_update_error));
						} else {
							showToast(context
									.getString(R.string.factory_pagetwo_key_file_no_exits));
						}
					} else {
						showToast(context
								.getString(R.string.factory_pagetwo_key_file_no_exits));
					}
				} else {
					showToast(context
							.getString(R.string.factory_reciver_no_usb));
				}
			}
		});

        final MenuItemData KeyMasterUpadate = new MenuItemData(
                "KeyMaster KEY Upgrade");
        KeyMasterUpadate.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "ESN KEY onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_KEYMASTER);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setKeyMaster(mFile.listFiles()[0]
                                    .getAbsolutePath())) {
                               // factorySetting.deleteFileByPath(mFile
                               //         .listFiles()[0].getAbsolutePath());
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            } else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        /**
         * zcj add 2018-11-7
         */
        final MenuItemData AllKeyUpadate = new MenuItemData("All KEY Upgrade");
        final File[] mKeyDirs = new File[Contants.mKeyPathStrings.length];
        final Boolean[] mKeyDirExistsBooleans = new Boolean[Contants.mKeyPathStrings.length];
        final Boolean[] mKeyFileExistsBooleans = new Boolean[Contants.mKeyPathStrings.length];
        final Boolean[] mKeyFileTvExistBooleans = new Boolean[Contants.mKeyPathStrings.length];
        final Boolean[] mKeyFileUpdatesBooleans = new Boolean[Contants.mKeyPathStrings.length];

        AllKeyUpadate.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "All Key Upadate");

                if (factorySetting.findUsbDir()) {

                    // String mShow = "Result:\n";
                    for (int id = 0; id < Contants.mKeyPathStrings.length; id++) {
                        mKeyDirs[id] = factorySetting
                                .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.mKeyPathStrings[id]);
                    }
                    for (int index = 0; index < mKeyDirs.length; index++) {
                        if (mKeyDirs[index].exists() && mKeyDirs[index].isDirectory()) {
                            mKeyDirExistsBooleans[index] = true;
                            mKeyFileUpdatesBooleans[index]=false;
                            // get the first key
                            if (mKeyDirs[index].listFiles().length > 0) {
                                mKeyFileExistsBooleans[index] = true;
                                File updatefile = mKeyDirs[index].listFiles()[0];
                                switch (index) {
                                    case Contants.KEY_TAG_CIPLUS: {
                                        if (factorySetting.isDTVCIPlusKeyExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setCIPlusKey(updatefile
                                                            .getAbsolutePath());
                                        }
                                    }
                                    break;
                                    /*case Contants.KEY_TAG_DEVICEID: {
                                        if (factorySetting.isDeviceIdExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setDeviceIDByPath(updatefile
                                                            .getAbsolutePath());
                                        }
                                    }
                                    break;*/
								case Contants.KEY_TAG_NETFLIX: {
									if (factorySetting.isNETFLIXKeyExist()
											&& factorySetting
													.getKeyUpgradeForce() == 0) {
										mKeyFileTvExistBooleans[index] = true;
										mKeyFileUpdatesBooleans[index] = false;
									} else {
										mKeyFileTvExistBooleans[index] = false;
										mKeyFileUpdatesBooleans[index] = factorySetting
												.setNetflixKey(updatefile
														.getAbsolutePath());
									}
								}
									break;
                                    case Contants.KEY_TAG_HDCP: {
                                        if (factorySetting.isHDCPKey2XExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setHdcpKey2x(updatefile
                                                            .getAbsolutePath());
                                        }
                                    }
                                    break;
                                    case Contants.KEY_TAG_HDCP14: {
                                        if (factorySetting.isHDCPKey1XExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setHdcpKey1x(updatefile
                                                            .getAbsolutePath());
                                        }
                                    }
                                    break;
                                    case Contants.KEY_TAG_KEYMASTER: {
                                        if (factorySetting.isKeyMasterExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setKeyMaster(updatefile
                                                            .getAbsolutePath());
                                        }
                                    }
                                    break;
                                    case Contants.KEY_TAG_WIDEVINE: {
                                        if (factorySetting.isWidevineKeyExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
										String fileName = updatefile.getName().substring(0,
												updatefile.getName().indexOf("."));
										mKeyFileUpdatesBooleans[index] = factorySetting.setWidevineKey(
												updatefile.getAbsolutePath()) && factorySetting.setDeviceID(fileName);
									}
								}
									break;

                                    case Contants.KEY_TAG_MAC: {
                                        if (factorySetting.isMacExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setMACAddr(updatefile
                                                            .getAbsolutePath());
                                        }
                                    }
                                    break;
                                    case Contants.KEY_TAG_PLAYREADY: {
                                        if (factorySetting.isPlayReadyKeyExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            boolean ret1 = false, ret2 = false;
                                            for (int i = 0; i < mKeyDirs[index]
                                                    .listFiles().length; i++) {
                                                File file = mKeyDirs[index]
                                                        .listFiles()[i];
                                                if (file.getAbsolutePath()
                                                        .contains(
                                                                Contants.KEY_STRING_PLAYREADY_1)) {
                                                    ret1 = factorySetting.setPlayReadyKey_1(file
                                                            .getAbsolutePath());
                                                } else if (file
                                                        .getAbsolutePath()
                                                        .contains(
                                                                Contants.KEY_STRING_PLAYREADY_2)) {
                                                    ret2 = factorySetting.setPlayReadyKey_2(file
                                                            .getAbsolutePath());
                                                } else {

                                                }
                                                //Log.d("zcj", file.getAbsolutePath());
                                            }

                                            mKeyFileUpdatesBooleans[index] = ret1
                                                    && ret2 && factorySetting.setPlayReadyKeyToIni("OK");
                                        }
                                    }
                                    break;
									/*
                                    case Contants.KEY_TAG_PLAYREADY25: {
                                        if (factorySetting.isPlayReadyKey25Exist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            boolean ret1 = false, ret2 = false;
                                            for (int i = 0; i < mKeyDirs[index]
                                                    .listFiles().length; i++) {
                                                File file = mKeyDirs[index]
                                                        .listFiles()[i];
                                                if (file.getAbsolutePath()
                                                        .contains(
                                                                Contants.KEY_STRING_PLAYREADY25_1)) {
                                                    ret1 = factorySetting.setPlayReadyKey25_1(file
                                                            .getAbsolutePath());
                                                } else if (file
                                                        .getAbsolutePath()
                                                        .contains(
                                                                Contants.KEY_STRING_PLAYREADY25_2)) {
                                                    ret2 = factorySetting.setPlayReadyKey25_2(file
                                                            .getAbsolutePath());
                                                } else {

                                                }
                                                //Log.d("zcj", file.getAbsolutePath());
                                            }

                                            mKeyFileUpdatesBooleans[index] = ret1
                                                    && ret2 && factorySetting.setPlayReadyKey25ToIni("OK");
                                        }
                                    }
                                    break;
									*/
                                    case Contants.KEY_TAG_WEBPLATFORM_CA: {
                                        if (factorySetting.isCLIENTCAKeyExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
											String caKeyPath=updatefile.getParentFile().getAbsolutePath();
											Log.d("CHFactoryTEST",caKeyPath);
                                            mKeyFileUpdatesBooleans[index] = factorySetting
                                                    .setCLIENTCAKey(caKeyPath);
                                        }
                                    }
                                    break;
                                    case Contants.KEY_TAG_PROJECT: {
                                        if (factorySetting.isProjectIdExist()
                                                && factorySetting
                                                .getKeyUpgradeForce() == 0) {
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        } else {
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index] = factorySetting.setProjectId(updatefile.getAbsolutePath());
                                        }
                                    }
                                    break;
                                    case Contants.KEY_TAG_HASHKEY:{
                                        if(!factorySetting.isHashKeyExist()
                                                || factorySetting.getHashKeyUpgradeForce()==0){
                                            String path=updatefile.getAbsolutePath().substring(0,updatefile.getAbsolutePath().lastIndexOf("/")+1);
                                            Log.d("CHFactory.page2",path);
                                            mKeyFileTvExistBooleans[index] = false;
                                            mKeyFileUpdatesBooleans[index]=factorySetting.setHashKey(path);
                                        }else{
                                            mKeyFileTvExistBooleans[index] = true;
                                            mKeyFileUpdatesBooleans[index] = false;
                                        }
                                    }
                                    break;

                                }

                                if (mKeyFileUpdatesBooleans[index]) {
                                    if (index == Contants.KEY_TAG_PROJECT
                                            || index == Contants.KEY_TAG_PLAYREADY
                                            || index == Contants.KEY_TAG_WEBPLATFORM_CA) {
                                        Log.d("zcj", "project key playready");

									} else if (index == Contants.KEY_TAG_NETFLIX) {
										// delete is move to setFunction
										/*
										 * boolean isdelete = factorySetting
										 * .deleteDirByPath(updatefile
										 * .getAbsolutePath());
										 */
									} else {
										/*
										 * delete is move to setFunction 
										 * boolean isdelete = factorySetting
										 * .deleteFileByPath(updatefile
										 * .getAbsolutePath()); Log.d("zcj",
										 * updatefile.getAbsolutePath() +
										 * " isdelete=" + (isdelete ? "true" :
										 * "false"));
										 */
									}
                                }
                            } else {
                                mKeyFileExistsBooleans[index] = false;
                                mKeyFileUpdatesBooleans[index] = false;
                                mKeyFileTvExistBooleans[index] = false;
                            }
                        } else {
                            mKeyFileExistsBooleans[index] = false;
                            mKeyDirExistsBooleans[index] = false;
                            mKeyFileUpdatesBooleans[index] = false;
                            mKeyFileTvExistBooleans[index] = false;
                        }
                    }
                    mKeyFileExistsBooleans[Contants.KEY_TAG_DEVICEID]=mKeyFileExistsBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
                    mKeyDirExistsBooleans[Contants.KEY_TAG_DEVICEID]=mKeyDirExistsBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
                    mKeyFileUpdatesBooleans[Contants.KEY_TAG_DEVICEID]=mKeyFileUpdatesBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
                    mKeyFileTvExistBooleans[Contants.KEY_TAG_DEVICEID]=mKeyFileTvExistBooleans[Contants.KEY_TAG_WIDEVINE];
                    //copyProjectIdFile();
                    FactoryKeyResultDialog mFactoryKeyResultDialog = new FactoryKeyResultDialog(
                            mFactoryActivity, mKeyDirExistsBooleans,
                            mKeyFileExistsBooleans, mKeyFileUpdatesBooleans,
                            mKeyFileTvExistBooleans);
                    mFactoryKeyResultDialog.show();
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        final MenuItemData mPlayReadyUpgrade = new MenuItemData(
                "Play Ready Upgrade");
        mPlayReadyUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "setPlayReadyKey onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_PLAYREADY);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            boolean ret1 = false, ret2 = false;
                            for (int i = 0; i < mFile.listFiles().length; i++) {
                                File file = mFile.listFiles()[i];
                                if (file.getAbsolutePath().contains(
                                        Contants.KEY_STRING_PLAYREADY_1)) {
                                    ret1 = factorySetting
                                            .setPlayReadyKey_1(file
                                                    .getAbsolutePath());
                                } else if (file.getAbsolutePath().contains(
                                        Contants.KEY_STRING_PLAYREADY_2)) {
                                    ret2 = factorySetting
                                            .setPlayReadyKey_2(file
                                                    .getAbsolutePath());
                                } else {

                                }
                                Log.d("zcj", file.getAbsolutePath());
                            }
                            if (ret1 && ret2 && factorySetting.setPlayReadyKeyToIni("OK"))
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });
		/*
        final MenuItemData mPlayReady25Upgrade = new MenuItemData(
                "Play Ready2.5 Upgrade");
        mPlayReady25Upgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "setPlayReadyKey25 onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_PLAYREADY25);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            boolean ret1 = false, ret2 = false;
                            for (int i = 0; i < mFile.listFiles().length; i++) {
                                File file = mFile.listFiles()[i];
                                if (file.getAbsolutePath().contains(
                                        Contants.KEY_STRING_PLAYREADY25_1)) {
                                    ret1 = factorySetting
                                            .setPlayReadyKey25_1(file
                                                    .getAbsolutePath());
                                } else if (file.getAbsolutePath().contains(
                                        Contants.KEY_STRING_PLAYREADY25_2)) {
                                    ret2 = factorySetting
                                            .setPlayReadyKey25_2(file
                                                    .getAbsolutePath());
                                } else {

                                }
                                Log.d("zcj", file.getAbsolutePath());
                            }
                            if (ret1 && ret2 && factorySetting.setPlayReadyKey25ToIni("OK"))
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });
		*/
        final MenuItemData mclientCAkeyUpgrade = new MenuItemData(
                "client CA key Upgrade");
        mclientCAkeyUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "client CA key onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_WEBPLATFORM_CA);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
							if (factorySetting.setCLIENTCAKey(mFile// .listFiles()[0]
                                    .getAbsolutePath()) ) {
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_success));
                            } else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        
        final MenuItemData mHashKeyUpgrade = new MenuItemData(
                "Hash Key Upgrade");
        mHashKeyUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "setHashKey onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_HASHKEY);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
							if (factorySetting.setHashKey(mFile.getAbsolutePath()))
								showToast(context.getString(R.string.factory_pagetwo_key_update_success));
                            else
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });

        final MenuItemData mProjectIdUpgrade = new MenuItemData(
                "Project Id Upgrade");
        mProjectIdUpgrade.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "set project");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/" + Contants.KEY_PATH_STRING_PROJECT);
                    if (mFile.exists() && mFile.isDirectory()) {
                        if (mFile.listFiles().length > 0) {
                            if (factorySetting.setProjectId(mFile.listFiles()[0]
                                    .getAbsolutePath())){
                                showToast(context
		                                        .getString(R.string.factory_pagetwo_key_update_success));

                            }else{
                                showToast(context
                                        .getString(R.string.factory_pagetwo_key_update_error));
                            }
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_key_file_no_exits));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });
        final MenuItemData BootLogoUpadate = new MenuItemData(
                "Boot Logo Upgrade");
        BootLogoUpadate.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "Boot Logo onkey");
                if (factorySetting.findUsbDir()) {
                    File mFile = factorySetting
                            .getFile(Contants.FACTORY_PAGE2_LOGO_UPDATE_PATH + "/" + Contants.FACTORY_PAGE2_LOGO_UPDATE_NAME);
                    File musicFile = factorySetting
                            .getFile(Contants.FACTORY_PAGE2_LOGO_UPDATE_PATH + "/" + Contants.FACTORY_PAGE2_MUSIC_UPDATE_NAME);
                    if (musicFile.exists()) {
                        mFile = musicFile;
                    }
                    if (mFile.exists()) {
                        if (factorySetting.changeBootLogoByPath(mFile.getAbsolutePath())) {

                            showToast(context
                                    .getString(R.string.factory_pagetwo_update_success));
                        } else {
                            showToast(context
                                    .getString(R.string.factory_pagetwo_update_error));
                        }
                    } else {
                        showToast(context
                                .getString(R.string.factory_pagetwo_key_file_no_exits));
                    }
                } else {
                    showToast(context
                            .getString(R.string.factory_reciver_no_usb));
                }
            }
        });
        final MenuItemData WriteToEeprom = new MenuItemData(
                "Write to Eeprom");
        WriteToEeprom.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("tv", "WriteToEeprom onkey");
                Intent intent = new Intent();
                intent.setPackage("com.mediatek.tv.factorykey");
                intent.setAction("com.mediatek.tv.factorykey.WriteToEeprom");
                mContext.startService(intent);
               
            }
        });

        final MenuItemData showEepromStatus = new MenuItemData(
                "Show Eeprom Status");
        final int EEPROM_STATUS_SHOW=5;
        showEepromStatus.setOnEnterKey(new MenuItemData.onEnterRightKey() {

            public void onEnterRightKey() {
                Log.v("wql", "keycode=KEYCODE_CHMIR_F11");
                Intent USBIntent = new Intent();
                USBIntent.setComponent(new ComponentName(
                        "com.homwee.factory",
                        "com.homwee.factory.FactoryListInfoActivity"));
                USBIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                USBIntent.putExtra("CheckItem", EEPROM_STATUS_SHOW);
                context.startActivity(USBIntent);

            }
        });

        mListItemData.add(netDetection);
		
        mListItemData.add(reloadEeprom);
			
        mListItemData.add(AllKeyUpadate);
        mListItemData.add(mProjectIdUpgrade);
        // mListItemData.add(ipAddress);
        // mListItemData.add(macAdress);
        mListItemData.add(manualSetMac);
        mListItemData.add(usbUpdateMac);
        //mListItemData.add(backupDataUsb);
        //remove CIPlusKeyUpadateForAuth
        //mListItemData.add(CIPlusKeyUpadateForAuth);
        mListItemData.add(BootLogoUpadate);
        mListItemData.add(usbUpdateDeviceID);
        mListItemData.add(mPlayReadyUpgrade);
        //mListItemData.add(mPlayReady25Upgrade);
        mListItemData.add(mHashKeyUpgrade);
        mListItemData.add(mHdcp1xUpgrade);
        mListItemData.add(mHdcp2xUpgrade);
        mListItemData.add(WidevineKeyUpadate);
        mListItemData.add(CIPlusKeyUpadate);
        mListItemData.add(KeyMasterUpadate);
        mListItemData.add(ESNKeyUpadate);
        mListItemData.add(mclientCAkeyUpgrade);
        mListItemData.add(mPQUpgrade);
        mListItemData.add(mAQUpgrade);
        mListItemData.add(screenDataUpgrade);
        mListItemData.add(PorductModelUpgrade);

        mListItemData.add(showEepromStatus);
        mListItemData.add(WriteToEeprom);

        if(factorySetting.isFactoryShowNoFunc()){
            mListItemData.add(BarcodeInfo);
        }

        // mListItemData.add(m6m40Upgrade);

        return mListItemData;
    }

    public void updateMAC() {
        macAdress.updateValue(factorySetting.getMAC());
    }

    byte GetMiracastHDCPKeyByteChecksum(byte[] key) // cHdcpBuffer 1024B
    {
        byte cTemp = 0, cRet = 0;
        int i;
        for (i = 0; i < (1280 - 1); i++) {
            cTemp += key[i];
        }
        cRet = (byte) (0x00 - cTemp);
        return cRet;
    }

    byte GetHDCPKeyByteChecksum(byte[] key) // cHdcpBuffer 1024B
    {
        byte cTemp = 0, cRet = 0;
        int i;
        for (i = 0; i < (512 - 1); i++) {
            cTemp += key[i];
        }
        cRet = (byte) (0x00 - cTemp);
        return cRet;
    }

    byte GetKeyByteChecksum(byte[] key) // cHdcpBuffer 1024B
    {
        byte cTemp = 0, cRet = 0;
        int i;
        for (i = 0; i < (key.length - 1); i++) {
            cTemp += key[i];
        }
        cRet = (byte) (0x00 - cTemp);
        return cRet;
    }

    boolean CheckCIPlusKeyValid(byte[] u8ciplusKey) {
        int bRet = -1;
        long u32CRC = 0;
        long u32CRCdata = 0;
        short u16CIPlusCrendentialsSize = 0;
        short u16Offset = 12;
        int CI_PLUS_KEY_LEN = u8ciplusKey.length;
        u32CRCdata += (long) (u8ciplusKey[CI_PLUS_KEY_LEN - 4] << 24);
        u32CRCdata += (long) (u8ciplusKey[CI_PLUS_KEY_LEN - 3] << 16);
        u32CRCdata += (long) (u8ciplusKey[CI_PLUS_KEY_LEN - 2] << 8);
        u32CRCdata += (long) (u8ciplusKey[CI_PLUS_KEY_LEN - 1]);

        u16CIPlusCrendentialsSize = (short) (u8ciplusKey[u16Offset] * 256 + u8ciplusKey[u16Offset + 1]);
        u32CRC = ~CRC32_Encode(u8ciplusKey, u16Offset
                + u16CIPlusCrendentialsSize);

        if (u32CRCdata == u32CRC) {
            bRet = 1;
        } else {
            bRet = 0;
        }

        return bRet == 1;
    }

    long CRC32_Encode(byte[] octets, int len) {
        long crc = 0xFFFFFFFF;
        long temp;
        short j;
        short i = 0;

        while ((len--) != 0) {
            temp = (long) ((crc & 0xFF) ^ octets[i++]);
            for (j = 0; j < 8; j++) {
                if ((temp & 0x1) == 1)
                    temp = (temp >> 1) ^ 0xEDB88320;
                else
                    temp >>= 1;
            }
            crc = (crc >> 8) ^ temp;
        }

        return crc ^ 0xFFFFFFFF;
    }

    public void showToast(String str) {
        if (mToast == null) {
            mToast = Toast.makeText(context, str, 5000);
        } else {
            mToast.setText(str);
            mToast.setDuration(5000 + 5000);
        }
        mToast.show();
    }

    public void copyFile(File srcFile,String des){
        factorySetting.copyFile(
                srcFile.getAbsolutePath(), Contants.FACTORY_PAGE2_TVCONFIG_PATH + "/" + srcFile.getName());
    }
    public void cancelToast() {
        if (mToast != null)
            mToast.cancel();
    }

    private void copyProjectIdFile() {

        if (factorySetting.findUsbDir()) {
            File file = factorySetting
                    .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/project_id.ini");
            if (file.exists()) {
                MtkTvFApiSystem.getInstance().copyFile(file.getAbsolutePath(), Contants.PATH_PROJECT_INI, false);
            }
        }

    }
}
